<script setup lang="ts">
  import startIcon from '@/static/images/start.png'
  import endIcon from '@/static/images/end.png'
  import carIcon from '@/static/images/car.png'
  import { onMounted } from 'vue'
  import AMapLoader from '@amap/amap-jsapi-loader'
  import type { ExpressData } from '@/types/order'

  interface Props {
    logisticsInfo: ExpressData
  }
  const props = defineProps<Props>()

  onMounted(async () => {
    ;(window as any)._AMapSecurityConfig = {
      securityJsCode: 'd38de6955019842e89194996a461e8dc',
    }

    // 获取物流信息
    const AMap = await AMapLoader.load({
      key: 'fc6bc3717c09e3d439823d9814eca279', // 申请好的Web端开发者Key，首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Scale'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    })

    let map = new AMap.Map('map', {})

    AMap.plugin(['AMap.Driving'], function () {
      const driving = new AMap.Driving({
        map: map, // 表示路线规划显示在创建的map实例上
        showTraffic: false,
        // 2.
        hideMarkers: true,
      })

      const start = props.logisticsInfo.logisticsInfo.pop()
      const end = props.logisticsInfo.logisticsInfo.shift()

      const startMarker = new AMap.Marker({
        position: [start?.longitude, start?.latitude],
        icon: startIcon,
        anchor: 'bottom-center',
      })

      const endMarker = new AMap.Marker({
        position: [end?.longitude, end?.latitude],
        icon: endIcon,
        anchor: 'bottom-center',
      })

      const carMarker = new AMap.Marker({
        position: [
          props.logisticsInfo.currentLocationInfo?.longitude,
          props.logisticsInfo.currentLocationInfo?.latitude,
        ],
        icon: carIcon,
        anchor: 'bottom-center',
      })

      map.add(startMarker)
      map.add(endMarker)
      map.add(carMarker)
      //获取起终点规划线路
      driving.search(
        [start?.longitude, start?.latitude],
        [end?.longitude, end?.latitude],
        {
          waypoints: props.logisticsInfo.logisticsInfo
            .map((item) => [item.longitude, item.latitude])
            .reverse(),
        }, 
        (status: any, result: any) => {
          if (status === 'complete') {
            setTimeout(() => {
              map.setFitView([carMarker])
              map.setZoom(10)
            }, 3000)
          } else {
            console.log('获取驾车数据失败：' + result)
          }
        }
      )   
    })

    // 3.创建标记
  })
</script>

<template>
  <view id="map" class="uni-map"></view>
</template>

<style lang="scss">
  .uni-map {
    width: 100%;
    height: 470px;
  }
</style>